<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇游戏 - 带速度控制</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
            color: #fff;
            padding: 20px;
        }
        
        .game-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
            max-width: 600px;
            width: 100%;
        }
        
        .header {
            text-align: center;
            width: 100%;
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.7);
        }
        
        .score-container {
            display: flex;
            justify-content: space-between;
            width: 100%;
            background: rgba(0, 0, 0, 0.4);
            padding: 15px;
            border-radius: 10px;
            font-size: 1.2rem;
        }
        
        canvas {
            background-color: #0d1b2a;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
            display: block;
        }
        
        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
            justify-content: center;
        }
        
        .speed-controls {
            display: flex;
            gap: 10px;
            background: rgba(0, 0, 0, 0.4);
            padding: 10px 15px;
            border-radius: 30px;
        }
        
        button {
            background: linear-gradient(to bottom, #4a5568, #2d3748);
            color: white;
            border: none;
            padding: 12px 25px;
            font-size: 1rem;
            border-radius: 30px;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
            min-width: 120px;
        }
        
        button:hover {
            background: linear-gradient(to bottom, #2b6cb0, #2c5282);
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.3);
        }
        
        button.active {
            background: linear-gradient(to bottom, #e53e3e, #c53030);
            box-shadow: 0 0 10px rgba(229, 62, 62, 0.5);
        }
        
        .instructions {
            background: rgba(0, 0, 0, 0.4);
            padding: 15px;
            border-radius: 10px;
            margin-top: 10px;
            width: 100%;
        }
        
        .instructions h2 {
            margin-bottom: 10px;
            text-align: center;
        }
        
        .instructions ul {
            list-style-type: none;
            padding: 0 10px;
        }
        
        .instructions li {
            margin-bottom: 8px;
            display: flex;
            align-items: center;
        }
        
        .instructions li::before {
            content: "•";
            color: #63b3ed;
            font-weight: bold;
            display: inline-block;
            width: 1em;
            margin-right: 10px;
        }
        
        .speed-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            background: rgba(255, 255, 255, 0.1);
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 0.9rem;
        }
        
        .speed-bar {
            width: 120px;
            height: 10px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 5px;
            overflow: hidden;
        }
        
        .speed-level {
            height: 100%;
            background: linear-gradient(to right, #4ade80, #f59e0b, #ef4444);
            width: 33%;
            transition: width 0.3s ease;
        }
        
        @media (max-width: 500px) {
            h1 {
                font-size: 2rem;
            }
            
            canvas {
                width: 95vw;
                height: 95vw;
            }
            
            .controls {
                flex-direction: column;
                align-items: center;
            }
            
            button {
                width: 100%;
                max-width: 280px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="header">
            <h1>🐍 贪吃蛇游戏 🍎</h1>
        </div>
        
        <div class="score-container">
            <div>得分: <span id="score">0</span></div>
            <div>长度: <span id="length">3</span></div>
            <div class="speed-indicator">
                <span>速度:</span>
                <div class="speed-bar">
                    <div class="speed-level" id="speedLevel"></div>
                </div>
            </div>
        </div>
        
        <canvas id="gameCanvas" width="400" height="400"></canvas>
        
        <div class="controls">
            <div class="speed-controls">
                <button id="slowBtn">慢速</button>
                <button id="mediumBtn" class="active">中速</button>
                <button id="fastBtn">快速</button>
            </div>
            <button id="startBtn">开始游戏</button>
            <button id="pauseBtn">暂停</button>
            <button id="restartBtn">重新开始</button>
        </div>
        
        <div class="instructions">
            <h2>游戏说明</h2>
            <ul>
                <li>使用键盘方向键(↑ ↓ ← →)控制蛇的移动方向</li>
                <li>吃到红色食物可以增加蛇的长度和得分</li>
                <li>撞到墙壁或自己的身体游戏结束</li>
                <li>每吃一个食物得10分</li>
                <li>使用速度按钮调整游戏难度：慢速(简单)、中速(中等)、快速(困难)</li>
            </ul>
        </div>
    </div>

    <script>
        // 获取Canvas元素和上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 游戏常量
        const BOX_SIZE = 20;
        const COLS = canvas.width / BOX_SIZE;
        const ROWS = canvas.height / BOX_SIZE;
        
        // 游戏变量
        let snake = [];
        let food = {};
        let direction = 'RIGHT';
        let nextDirection = 'RIGHT';
        let score = 0;
        let gameSpeed = 150; // 毫秒（初始速度）
        let gameRunning = false;
        let gameLoopId = null;
        let currentSpeedLevel = 'medium'; // 当前速度级别
        
        // DOM元素
        const scoreElement = document.getElementById('score');
        const lengthElement = document.getElementById('length');
        const speedLevelElement = document.getElementById('speedLevel');
        const startBtn = document.getElementById('startBtn');
        const pauseBtn = document.getElementById('pauseBtn');
        const restartBtn = document.getElementById('restartBtn');
        const slowBtn = document.getElementById('slowBtn');
        const mediumBtn = document.getElementById('mediumBtn');
        const fastBtn = document.getElementById('fastBtn');
        
        // 初始化游戏
        function initGame() {
            // 初始化蛇 (初始长度为3)
            snake = [
                {x: 10, y: 10},
                {x: 9, y: 10},
                {x: 8, y: 10}
            ];
            
            // 初始方向
            direction = 'RIGHT';
            nextDirection = 'RIGHT';
            
            // 重置分数
            score = 0;
            scoreElement.textContent = score;
            lengthElement.textContent = snake.length;
            
            // 设置初始速度
            setSpeed('medium');
            
            // 生成食物
            generateFood();
            
            // 绘制初始游戏状态
            draw();
        }
        
        // 设置游戏速度[6](@ref)
        function setSpeed(level) {
            // 移除所有按钮的active类
            slowBtn.classList.remove('active');
            mediumBtn.classList.remove('active');
            fastBtn.classList.remove('active');
            
            // 根据级别设置速度
            switch(level) {
                case 'slow':
                    gameSpeed = 300; // 慢速
                    slowBtn.classList.add('active');
                    speedLevelElement.style.width = '33%';
                    currentSpeedLevel = 'slow';
                    break;
                case 'medium':
                    gameSpeed = 200; // 中速
                    mediumBtn.classList.add('active');
                    speedLevelElement.style.width = '66%';
                    currentSpeedLevel = 'medium';
                    break;
                case 'fast':
                    gameSpeed = 100; // 快速
                    fastBtn.classList.add('active');
                    speedLevelElement.style.width = '100%';
                    currentSpeedLevel = 'fast';
                    break;
            }
            
            // 如果游戏正在运行，重新设置定时器[6](@ref)
            if (gameRunning) {
                clearInterval(gameLoopId);
                gameLoopId = setInterval(gameLoop, gameSpeed);
            }
        }
        
        // 生成食物（确保不在蛇身上）
        function generateFood() {
            let newFood;
            let onSnake;
            
            do {
                onSnake = false;
                newFood = {
                    x: Math.floor(Math.random() * COLS),
                    y: Math.floor(Math.random() * ROWS)
                };
                
                // 检查食物是否出现在蛇身上
                for (let i = 0; i < snake.length; i++) {
                    if (snake[i].x === newFood.x && snake[i].y === newFood.y) {
                        onSnake = true;
                        break;
                    }
                }
            } while (onSnake);
            
            food = newFood;
        }
        
        // 绘制游戏
        function draw() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格背景
            ctx.fillStyle = '#14213d';
            for (let x = 0; x < COLS; x++) {
                for (let y = 0; y < ROWS; y++) {
                    if ((x + y) % 2 === 0) {
                        ctx.fillRect(x * BOX_SIZE, y * BOX_SIZE, BOX_SIZE, BOX_SIZE);
                    }
                }
            }
            
            // 绘制蛇
            snake.forEach((segment, index) => {
                // 蛇头
                if (index === 0) {
                    ctx.fillStyle = '#4ade80';
                    ctx.fillRect(segment.x * BOX_SIZE, segment.y * BOX_SIZE, BOX_SIZE, BOX_SIZE);
                    
                    // 蛇头眼睛
                    ctx.fillStyle = '#000';
                    const eyeSize = BOX_SIZE / 5;
                    
                    // 根据方向调整眼睛位置
                    if (direction === 'RIGHT') {
                        ctx.fillRect((segment.x * BOX_SIZE) + BOX_SIZE - eyeSize*2, 
                                    (segment.y * BOX_SIZE) + eyeSize*2, eyeSize, eyeSize);
                        ctx.fillRect((segment.x * BOX_SIZE) + BOX_SIZE - eyeSize*2, 
                                    (segment.y * BOX_SIZE) + BOX_SIZE - eyeSize*3, eyeSize, eyeSize);
                    } else if (direction === 'LEFT') {
                        ctx.fillRect((segment.x * BOX_SIZE) + eyeSize, 
                                    (segment.y * BOX_SIZE) + eyeSize*2, eyeSize, eyeSize);
                        ctx.fillRect((segment.x * BOX_SIZE) + eyeSize, 
                                    (segment.y * BOX_SIZE) + BOX_SIZE - eyeSize*3, eyeSize, eyeSize);
                    } else if (direction === 'UP') {
                        ctx.fillRect((segment.x * BOX_SIZE) + eyeSize*2, 
                                    (segment.y * BOX_SIZE) + eyeSize, eyeSize, eyeSize);
                        ctx.fillRect((segment.x * BOX_SIZE) + BOX_SIZE - eyeSize*3, 
                                    (segment.y * BOX_SIZE) + eyeSize, eyeSize, eyeSize);
                    } else { // DOWN
                        ctx.fillRect((segment.x * BOX_SIZE) + eyeSize*2, 
                                    (segment.y * BOX_SIZE) + BOX_SIZE - eyeSize*2, eyeSize, eyeSize);
                        ctx.fillRect((segment.x * BOX_SIZE) + BOX_SIZE - eyeSize*3, 
                                    (segment.y * BOX_SIZE) + BOX_SIZE - eyeSize*2, eyeSize, eyeSize);
                    }
                } 
                // 蛇身
                else {
                    ctx.fillStyle = '#38b2ac';
                    ctx.fillRect(segment.x * BOX_SIZE, segment.y * BOX_SIZE, BOX_SIZE, BOX_SIZE);
                    
                    // 蛇身纹理
                    ctx.fillStyle = '#2c7a7b';
                    ctx.fillRect(segment.x * BOX_SIZE + BOX_SIZE/4, segment.y * BOX_SIZE + BOX_SIZE/4, BOX_SIZE/2, BOX_SIZE/2);
                }
            });
            
            // 绘制食物
            ctx.fillStyle = '#e53e3e';
            ctx.beginPath();
            ctx.arc(
                food.x * BOX_SIZE + BOX_SIZE/2, 
                food.y * BOX_SIZE + BOX_SIZE/2, 
                BOX_SIZE/2 - 2, 
                0, 
                Math.PI * 2
            );
            ctx.fill();
            
            // 食物光泽效果
            ctx.fillStyle = '#fff';
            ctx.beginPath();
            ctx.arc(
                food.x * BOX_SIZE + BOX_SIZE/3, 
                food.y * BOX_SIZE + BOX_SIZE/3, 
                BOX_SIZE/8, 
                0, 
                Math.PI * 2
            );
            ctx.fill();
        }
        
        // 移动蛇
        function moveSnake() {
            // 更新方向
            direction = nextDirection;
            
            // 计算新头部位置
            const head = {x: snake[0].x, y: snake[0].y};
            
            switch (direction) {
                case 'UP':
                    head.y -= 1;
                    break;
                case 'DOWN':
                    head.y += 1;
                    break;
                case 'LEFT':
                    head.x -= 1;
                    break;
                case 'RIGHT':
                    head.x += 1;
                    break;
            }
            
            // 检查是否撞墙
            if (head.x < 0 || head.x >= COLS || head.y < 0 || head.y >= ROWS) {
                gameOver();
                return;
            }
            
            // 检查是否撞到自己
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === head.x && snake[i].y === head.y) {
                    gameOver();
                    return;
                }
            }
            
            // 添加新头部
            snake.unshift(head);
            
            // 检查是否吃到食物
            if (head.x === food.x && head.y === food.y) {
                // 增加分数
                score += 10;
                scoreElement.textContent = score;
                
                // 更新长度显示
                lengthElement.textContent = snake.length;
                
                // 生成新食物
                generateFood();
                
                // 随着蛇变长，游戏速度逐渐加快（但不超过最小速度）[6,8](@ref)
                if (gameSpeed > 60 && snake.length % 3 === 0) {
                    gameSpeed -= 5;
                    clearInterval(gameLoopId);
                    gameLoopId = setInterval(gameLoop, gameSpeed);
                    
                    // 更新速度指示器
                    if (gameSpeed > 130) {
                        setSpeed('slow');
                    } else if (gameSpeed > 90) {
                        setSpeed('medium');
                    } else {
                        setSpeed('fast');
                    }
                }
            } else {
                // 如果没有吃到食物，移除尾部
                snake.pop();
            }
            
            // 重绘游戏
            draw();
        }
        
        // 游戏主循环
        function gameLoop() {
            if (gameRunning) {
                moveSnake();
            }
        }
        
        // 游戏结束
        function gameOver() {
            gameRunning = false;
            clearInterval(gameLoopId);
            gameLoopId = null;
            
            // 显示最终得分
            setTimeout(() => {
                alert(`游戏结束！\n最终得分: ${score}\n蛇的长度: ${snake.length}`);
            }, 100);
        }
        
        // 开始游戏
        function startGame() {
            if (!gameRunning) {
                gameRunning = true;
                if (!gameLoopId) {
                    gameLoopId = setInterval(gameLoop, gameSpeed);
                }
            }
        }
        
        // 暂停游戏
        function pauseGame() {
            gameRunning = !gameRunning;
            pauseBtn.textContent = gameRunning ? '暂停' : '继续';
        }
        
        // 键盘控制
        function handleKeydown(e) {
            if (!gameRunning) return;
            
            switch (e.key) {
                case 'ArrowUp':
                    if (direction !== 'DOWN') nextDirection = 'UP';
                    break;
                case 'ArrowDown':
                    if (direction !== 'UP') nextDirection = 'DOWN';
                    break;
                case 'ArrowLeft':
                    if (direction !== 'RIGHT') nextDirection = 'LEFT';
                    break;
                case 'ArrowRight':
                    if (direction !== 'LEFT') nextDirection = 'RIGHT';
                    break;
            }
        }
        
        // 按钮事件监听
        startBtn.addEventListener('click', startGame);
        pauseBtn.addEventListener('click', pauseGame);
        restartBtn.addEventListener('click', () => {
            clearInterval(gameLoopId);
            gameLoopId = null;
            initGame();
            gameRunning = true;
            gameLoopId = setInterval(gameLoop, gameSpeed);
        });
        
        // 速度控制按钮事件监听
        slowBtn.addEventListener('click', () => setSpeed('slow'));
        mediumBtn.addEventListener('click', () => setSpeed('medium'));
        fastBtn.addEventListener('click', () => setSpeed('fast'));
        
        // 键盘事件监听
        document.addEventListener('keydown', handleKeydown);
        
        // 初始化游戏
        initGame();
    </script>
</body>
</html>